#include "ChangeRecParser.h"

#include "ApprovalParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

ChangeRecParser::ChangeRecParser(
    QStringParser *&_dateTimeParser
    , QStringParser *&_personRefParser
    , QStringParser *&_applicationParser
    , QStringParser *&_changeParser
    , ApprovalParser *&_approvalParser
):    m_dateTimeParser(_dateTimeParser)
    , m_personRefParser(_personRefParser)
    , m_applicationParser(_applicationParser)
    , m_changeParser(_changeParser)
    , m_approvalParser(_approvalParser)
{

}

bool ChangeRecParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new ChangeRec());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("dateTime")))
    {
        data = reader->attributes().value(QStringLiteral("dateTime"));
        if (!m_dateTimeParser->parse(reader, data))
            return false;
        m_result->dateTime = m_dateTimeParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("dateTime: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("personRef")))
    {
        data = reader->attributes().value(QStringLiteral("personRef"));
        if (!m_personRefParser->parse(reader, data))
            return false;
        m_result->personRef = m_personRefParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("personRef: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("application")))
    {
        data = reader->attributes().value(QStringLiteral("application"));
        if (!m_applicationParser->parse(reader, data))
            return false;
        m_result->application = m_applicationParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("application: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("change")))
    {
        data = reader->attributes().value(QStringLiteral("change"));
        if (!m_changeParser->parse(reader, data))
            return false;
        m_result->change = m_changeParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("change: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Approval"))
        {
            if (!m_approvalParser->parse(reader))
                return false;
            auto result = m_approvalParser->result();
            m_result->approvalList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

ChangeRec *ChangeRecParser::result()
{
    return m_result.take();
}

}